<script setup>
import { reactive, ref } from "vue";
import { loginService, registerService } from "@/api/userAPI";
import { ElMessage } from "element-plus";

const loginOrRegister = ref(true);
const formRef = ref(null);

//定义表单数据
const form = reactive({
  username: "",
  password: "",
  rePassword: "",
});
//登录操作
const onSubmit = () => {
  formRef.value.validate(async (valid) => {
    console.log(valid);
    if (!valid) {
      ElMessage.error("必填项不能为空！");
      return false;
    }

    let data = await loginService(form);
    if (data.code !== 200) {
      return ElMessage.error(data.message);
    }
    console.log(data);
    localStorage.setItem("Authorization", data.data.token);
    localStorage.setItem("userInfo", JSON.stringify(data.data));
    window.location.href = "/layout";
  });
};
//注册操作
const onRegister = async () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      return false;
    }

    if (form.password !== form.rePassword) {
      return ElMessage.error("两次密码不一致！");
    }
    await registerService(form);
    ElMessage({
      message: "注册成功！",
      type: "success",
    });
    setTimeout(() => {
      window.location.href = "/login";
    }, 300);
  });
};
</script>

<template>
  <img src="@/assets/images/9374.jpg" />
  <div class="login">
    <el-form :model="form" label-width="auto" style="max-width: 600px" ref="formRef">
      <el-form-item label="用户名" prop="username" :rules="[
        { required: true, message: '请输入用户名！', trigger: 'blur' },
      ]">
        <el-input v-model="form.username" placeholder="请输入用户名！" />
      </el-form-item>
      <el-form-item label="密码" prop="password" :rules="[{ required: true, message: '请输入密码！', trigger: 'blur' }]">
        <el-input v-model="form.password" placeholder="请输入密码！" show-password />
      </el-form-item>
      <el-form-item v-if="!loginOrRegister" label="确认密码" prop="rePassword" :rules="[
        { required: true, message: '请输入确认密码！', trigger: 'blur' },
      ]">
        <el-input v-model="form.rePassword" placeholder="请确认密码！" show-password />
      </el-form-item>
      <el-form-item>
        <el-button v-if="loginOrRegister" type="primary" @click="onSubmit">登陆</el-button>
        <el-button v-else type="primary" @click="onRegister">注册</el-button>
        <el-button v-if="!loginOrRegister" type="primary" @click="loginOrRegister = true">返回登录</el-button>
        <el-button v-else @click="loginOrRegister = false">去注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
img {
  width: 100vw;
  height: 100vh;
}

.login {
  width: 350px;
  position: absolute;
  top: 70%;
  left: 60%;
  transform: translate(-50%, -50%);
  background-color: #f5f5f5;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 41%);
  opacity: 0.9;
}
</style>
